(function () {
    var paper,
        midObj = {},
        $win = $(window),
        winHt = $win.height(),
        winWt = $win.width(),
        mq = {
            fontSize: 16,
            numFtSize: 16,
            currentWeek: "Current Week",
            gridWidth: 145,
            devWidth: 100,
            gapWidth: 1,
            gapHeight: 1
        },
        timeHandle,
        loopTimeSpan = 15000,
        svgTableDict = {},
        totalValDict = {},
        lineRateCache = {};
    var gridRowNum = 3,
        gridColNum = 2;

    if (winHt > winWt) {
        winWt = 2 * winWt;
    }

    var getTotalVal = function (type, idx) {
        var tv = 0;
        if (totalValDict[type] && totalValDict[type][idx]) {
            tv = totalValDict[type][idx];
        }
        if (idx == 'deviation') {
            if (tv < 0) {
                tv = {
                    text: tv,
                    fill: '#f00'
                }
            }
        }
        return tv;
    };

    var clacTotalVal = function (apiData) {
        totalValDict = {};
        $.each(apiData, function (i, o) {
            if (!totalValDict['day']) {
                totalValDict['day'] = {};
                totalValDict['week'] = {};
            }
            try {
                totalValDict['day']['target'] = (totalValDict['day']['target'] || 0) + parseInt(o[0]['today']);
                totalValDict['day']['current'] = (totalValDict['day']['current'] || 0) + parseInt(o[1]['today']);
                totalValDict['day']['forecast'] = (totalValDict['day']['forecast'] || 0) + parseInt(o[2]['today']);
                totalValDict['day']['planned'] = (totalValDict['day']['planned'] || 0) + parseInt(o[3]['today']);
                totalValDict['day']['deviation'] = (totalValDict['day']['deviation'] || 0) + parseInt(o[4]['today']);
                totalValDict['week']['target'] = (totalValDict['week']['target'] || 0) + parseInt(o[0]['current_week']);
                totalValDict['week']['current'] = (totalValDict['week']['current'] || 0) + parseInt(o[1]['current_week']);
                totalValDict['week']['forecast'] = (totalValDict['week']['forecast'] || 0) + parseInt(o[2]['current_week']);
                totalValDict['week']['planned'] = (totalValDict['week']['planned'] || 0) + parseInt(o[3]['current_week']);
                totalValDict['week']['deviation'] = (totalValDict['week']['deviation'] || 0) + parseInt(o[4]['current_week']);
            }
            catch (e) {
            }
        });
    };

    var redrawGridDynamicContent = function (apiData) {
        var casting_list = ['B38A', 'B38B', 'B48A', 'B48B'],
            type_list = ['today', 'current_week'],
            len = type_list.length,
            idx_list = ['00', '01', '10', '11'];
        clacTotalVal(apiData);
        drawLineRate(true);
        $.each(casting_list, function (i, v) {
            var idx = idx_list[i];
            var svgTable = svgTableDict[idx];
            var rd = apiData[v],
                n = 0;
            for (n; n < len; n++) {
                var tName = type_list[n];
                if (rd[1][tName] > 0 && rd[1][tName] < rd[3][tName]) {
                    var text = rd[1][tName];
                    rd[1][tName] = {
                        fill: '#f00',
                        text: text
                    }
                }
                else {
                    var text = rd[1][tName];
                    rd[1][tName] = {
                        fill: '#0f0',
                        text: text
                    }
                }
                if (rd[2][tName] > 0 && rd[2][tName] < rd[0][tName]) {
                    var text = rd[2][tName];
                    rd[2][tName] = {
                        fill: '#f00',
                        text: text
                    }
                } else {
                    var text = rd[2][tName];
                    rd[2][tName] = {
                        fill: '#0f0',
                        text: text
                    }
                }

                if (rd[4][tName] < 0) {
                    var text = rd[4][tName];
                    rd[4][tName] = {
                        fill: '#f00',
                        text: text
                    }
                } else {
                    var text = rd[4][tName];
                    rd[4][tName] = {
                        fill: '#0f0',
                        text: text
                    }
                }
            }
            svgTable.setRowData(rd);
            svgTable.draw(true);
        });
        var svgTable = svgTableDict['20'],
            rd = [
                {"value": getTotalVal('day', 'target')},
                {"value": getTotalVal('day', 'current')},
                {"value": getTotalVal('day', 'forecast')},
                {"value": getTotalVal('day', 'planned')},
                {"value": getTotalVal('day', 'deviation')}
            ],
            tName = 'value';
        if (rd[1][tName] > 0 && rd[1][tName] < rd[3][tName]) {
            var text = rd[1][tName];
            rd[1][tName] = {
                fill: '#f00',
                text: text
            }
        }
        else {
            var text = rd[1][tName];
            rd[1][tName] = {
                fill: '#0f0',
                text: text
            }
        }
        if (rd[2][tName] > 0 && rd[2][tName] < rd[0][tName]) {
            var text = rd[2][tName];
            rd[2][tName] = {
                fill: '#f00',
                text: text
            }
        } else {
            var text = rd[2][tName];
            rd[2][tName] = {
                fill: '#0f0',
                text: text
            }
        }
        svgTable.setRowData(rd);
        svgTable.draw(true);
        var svgTable = svgTableDict['21'],
            rd = [
                {"value": getTotalVal('week', 'target')},
                {"value": getTotalVal('week', 'current')},
                {"value": getTotalVal('week', 'forecast')},
                {"value": getTotalVal('week', 'planned')},
                {"value": getTotalVal('week', 'deviation')}
            ],
            tName = 'value';
        if (rd[1][tName] > 0 && rd[1][tName] < rd[3][tName]) {
            var text = rd[1][tName];
            rd[1][tName] = {
                fill: '#f00',
                text: text
            }
        }
        else {
            var text = rd[1][tName];
            rd[1][tName] = {
                fill: '#0f0',
                text: text
            }
        }
        if (rd[2][tName] > 0 && rd[2][tName] < rd[0][tName]) {
            var text = rd[2][tName];
            rd[2][tName] = {
                fill: '#f00',
                text: text
            }
        } else {
            var text = rd[2][tName];
            rd[2][tName] = {
                fill: '#0f0',
                text: text
            }
        }
        svgTable.setRowData(rd);
        svgTable.draw(true);
    };

    var initEnvData = function () {
        $.ajax({
            url: '/NEP/ALS/api/rtb2?timestamp=' + Date.now(),
            dataType: 'json',
            success: function (resp) {
                if (resp) {
                    if (resp['rtb2_data']) {
                        redrawGridDynamicContent(resp['rtb2_data']);
                    }
                }
            }
        });
    };

    var initLayout = function () {
        paper = Raphael('stage', winWt, winHt);
        calcBoardSize();
        initEnvData();
        timeHandle = setInterval(function () {
            initEnvData();
        }, loopTimeSpan);
    };

    var calcBoardSize = function () {
        $('#stage').css({
            width: winWt + 'px',
            height: winHt + 'px',
            overflow: 'hidden'
        });
        midObj.boardXAxis = 0; // board 起始x坐标
        midObj.boardYAxis = 0; // board 起始y坐标

        midObj.lineRateHt = 60;

        midObj.boardWt = winWt - midObj.boardXAxis;
        midObj.boardHt = winHt - midObj.lineRateHt;

        midObj.boardGrid = [];
        midObj.boardGapWt = mq['gapWidth'];
        midObj.boardGapHt = mq['gapHeight'];
        midObj.boardGridItemWt = parseInt((midObj.boardWt - (gridColNum - 1) * midObj.boardGapWt) / gridColNum);
        midObj.boardGridItemHt = parseInt((midObj.boardHt - (gridRowNum - 1) * midObj.boardGapHt) / gridRowNum);
        var i = 0;
        for (i; i < gridRowNum; i++) {
            var j = 0;
            for (j; j < gridColNum; j++) {
                drawGrid(i, j);
            }
        }
        drawLineRate();
    };

    var drawLineRate = function (redraw) {
        if (redraw) {
            var date = new Date(),
                y = date.getFullYear(),
                m = date.getMonth() + 1,
                d = date.getDate(),
                paddingNum = function (n) {
                    if (n < 10) {
                        n = '0' + n;
                    }
                    return n;
                };
            var ds = y + '/' + paddingNum(m) + '/' + paddingNum(d) + ' 06:00:00',
                ts = (new Date(ds)).getTime() / 1000,
                nts = parseInt((new Date()).getTime() / 1000),
                nh = parseInt((nts - ts) / 360) / 10,
                rate = nh != 0 ? parseInt(totalValDict['day']['current'] * 100 / nh) / 100 : 0;
            lineRateCache['text'].attr({
                text: 'Current line rate = ' + rate + ' U/H'
            });
        }
        else {
            var x = midObj.boardXAxis,
                y = midObj.boardYAxis + 3 * (midObj.boardGridItemHt + midObj.boardGapHt),
                wt = midObj.boardWt,
                ht = midObj.lineRateHt - midObj.boardGapHt;
            paper.rect(x, y, wt, ht).attr({fill: '#000', 'stroke-width': 0, 'stroke': '#000'});
            lineRateCache['text'] = paper.text(x + 12, y + 30, 'Current line rate = Loading...').attr({
                'text-anchor': 'start',
                'font-size': 20,
                'font-weight': 900,
                'fill': '#0f0'
            });
        }
    };

    var drawGrid = function (rn, cn) {
        var gx = midObj.boardXAxis + cn * (midObj.boardGridItemWt + midObj.boardGapWt),
            gy = midObj.boardYAxis + rn * (midObj.boardGridItemHt + midObj.boardGapHt),
            castingList = ['B38A', 'B38B', 'B48A', 'B48B'];
        if (rn < 2) {
            var ops = {
                x: gx,
                y: gy,
                width: midObj.boardGridItemWt,
                height: midObj.boardGridItemHt,
                r: 0,
                bgColor: '#000',
                rowNum: 6,
                colNum: 3,
                fontSize: mq['fontSize'],
                columns: [
                    {"data": "casting_name", "text": castingList[2 * rn + cn], "align": "end", bgColor: '#000', width: mq['devWidth']},
                    {"data": "today", "text": "Today", "align": "middle", bgColor: '#000'},
                    {"data": "current_week", "text": mq['currentWeek'], "align": "middle", bgColor: '#000', width: 125}
                ]
            };
            var idx = rn + '' + cn;
            var svgTable = new SVGTable(ops, paper);
            svgTableDict[idx] = svgTable;
            svgTable.setRowData([
                {"casting_name": "Target", "today": {text: '-', fontSize: mq['numFtSize']}, "current_week": {text: '-', fontSize: mq['numFtSize']}},
                {"casting_name": "Current", "today": {text: '-', fontSize: mq['numFtSize']}, "current_week": {text: '-', fontSize: mq['numFtSize']}},
                {"casting_name": "Forecast", "today": {text: '-', fontSize: mq['numFtSize']}, "current_week": {text: '-', fontSize: mq['numFtSize']}},
                {"casting_name": "Planned", "today": {text: '-', fontSize: mq['numFtSize']}, "current_week": {text: '-', fontSize: mq['numFtSize']}},
                {"casting_name": "Deviation", "today": {text: '-', fontSize: mq['numFtSize']}, "current_week": {text: '-', fontSize: mq['numFtSize']}}
            ]);
            svgTable.draw();
        }
        else if (rn == 2) {
            var co = [{
                columns: [
                    {"data": "field", "text": "Total Day", "align": "middle", colspan: 2, width: mq['gridWidth'], bgColor: '#000'},
                    {"data": "value", "align": "middle", bgColor: '#000'}
                ]
            }, {
                columns: [
                    {"data": "field", "text": "Total Week", "align": "middle", colspan: 2, width: mq['gridWidth'], bgColor: '#000'},
                    {"data": "value", "align": "middle", bgColor: '#000'}
                ]
            }];
            var ops = {
                x: gx,
                y: gy,
                width: midObj.boardGridItemWt,
                height: midObj.boardGridItemHt,
                r: 0,
                bgColor: '#000',
                rowNum: 6,
                colNum: 2,
                fontSize: mq['fontSize']
            };
            if (co[cn]) {
                $.extend(ops, co[cn]);
            }
            var idx = rn + '' + cn;
            var svgTable = new SVGTable(ops, paper);
            svgTable.setRowData([
                {"field": {text: "Target Sum", align: "end"}, "value": {text: '-', fontSize: mq['numFtSize']}},
                {"field": {text: "Current Sum", align: "end"}, "value": {text: '-', fontSize: mq['numFtSize']}},
                {"field": {text: "Forecast Sum", align: "end"}, "value": {text: '-', fontSize: mq['numFtSize']}},
                {"field": {text: "Planned Sum", align: "end"}, "value": {text: '-', fontSize: mq['numFtSize']}},
                {"field": {text: "Deviation Sum", align: "end"}, "value": {text: '-', fontSize: mq['numFtSize']}}
            ]);
            svgTableDict[idx] = svgTable;
            svgTable.draw();
        }
    };

    $(function () {
        initLayout();
    });
})();